﻿using System;
using System.Diagnostics;

namespace NetMicro.Trace.Extensions
{
    /// <summary>
    /// 链路跟踪扩展
    /// </summary>
    internal static class ActivityExtensions
    {
        /// <summary>
        /// 获取跨度id
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        public static string GetSpanId(this Activity activity)
        {

            ArgumentNullException.ThrowIfNull(activity);
            var spanId = activity.IdFormat switch
            {
                ActivityIdFormat.Hierarchical => activity.Id,
                ActivityIdFormat.W3C => activity.SpanId.ToHexString(),
                ActivityIdFormat.Unknown => null,
                _ => null,
            };

            return spanId ?? string.Empty;
        }

        /// <summary>
        /// 获取跟踪id
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        public static string GetTraceId(this Activity activity)
        {
            ArgumentNullException.ThrowIfNull(activity);
            var traceId = activity.IdFormat switch
            {
                ActivityIdFormat.Hierarchical => activity.RootId,
                ActivityIdFormat.W3C => activity.TraceId.ToHexString(),
                ActivityIdFormat.Unknown => null,
                _ => null,
            };

            return traceId ?? string.Empty;
        }

        /// <summary>
        /// 获取父级id
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        public static string GetParentId(this Activity activity)
        {
            ArgumentNullException.ThrowIfNull(activity);
            var parentId = activity.IdFormat switch
            {
                ActivityIdFormat.Hierarchical => activity.ParentId,
                ActivityIdFormat.W3C => activity.ParentSpanId.ToHexString(),
                ActivityIdFormat.Unknown => null,
                _ => null,
            };
            return parentId ?? string.Empty;
        }
    }
}
